import React, { useEffect, useRef, useState } from 'react';
import { getToken } from '@/zero/utils/token';

const Index = (props) => {
  const iframeRef = useRef(null);

  const {
    src,
    defaultPageNumber = 1,
    search,
    headers,
    extParams,
    width = '100%',
    height = 'calc(100vh - 155px)',
    style,
    ...rest
  } = props;

  const [iframeReady, setIframeReady] = useState(false);

  useEffect(() => {
    if (iframeReady) {
      const newApplication = iframeRef.current?.contentWindow?.PDFViewerApplication;
      if (newApplication && src) {
        newApplication.open(src, {
          ...extParams,
          httpHeaders: {
            Authorization: getToken(),
            ...headers,
          },
        });
      }
    }
  }, [iframeReady, src]);

  useEffect(() => {
    if (iframeReady) {
      const timer = setInterval(() => {
        const newApplication = iframeRef.current?.contentWindow?.PDFViewerApplication;
        if (
          newApplication &&
          newApplication.initialized &&
          newApplication.isInitialViewSet &&
          newApplication.downloadComplete
        ) {
          if (search) {
            newApplication.findBar.open();
            newApplication.findBar.findField.value = search;
            newApplication.findBar.highlightAll.checked = true;
            newApplication.findBar.dispatchEvent('');
          }
          clearInterval(timer);
        }
      }, 1500);
    }
  }, [iframeReady, src, search]);

  return (
    <iframe
      ref={iframeRef}
      title="viewer"
      frameBorder={0}
      width={width}
      height={height}
      style={{
        ...style,
        width,
        height,
      }}
      src={`/parties/pdfjs-dist/web/viewer.html?file=#page=${defaultPageNumber}`}
      onLoad={() => {
        setIframeReady(true);
      }}
      {...rest}
    />
  );
};

Index.displayName = 'PdfViewer';
export default Index;
